/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-30 15:40:52   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.domain.OrderLog;
import com.zx.cloud.domain.OverdueDetail;
import com.zx.cloud.domain.RepayDetail;
import com.zx.cloud.domain.RepayOrder;
import com.zx.cloud.domain.User;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.OrderLogMapper;
import com.zx.cloud.persistence.OverdueDetailMapper;
import com.zx.cloud.persistence.RepayDetailMapper;
import com.zx.cloud.persistence.RepayOrderMapper;
import com.zx.cloud.persistence.UserMapper;
import com.zx.cloud.util.DateTimeUtil;
import com.zx.cloud.util.Page;
import com.zx.cloud.util.SmsCodeUtil;

/**
 * 还款订单表
 */
@Transactional
@Service
public class RepayOrderService extends CrudServiceImpl<RepayOrder> {

	private static final Logger LOGGER = LoggerFactory.getLogger(RepayOrderService.class);
	@Autowired
	private RepayOrderMapper repayOrderMapper;
	
	@Autowired
	private OverdueDetailMapper  overdueDetailMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private DictService dictService;
	@Autowired
	private RepayDetailMapper repayDetailMapper;
	
	
	@Autowired
	public RepayOrderService(CrudMapper<RepayOrder> mapper) {
		super(mapper);
	}

	/**
	 * @Description:贷后管理-还款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<RepayOrder> pageRepayOrder(RepayOrder entity) {
		entity.setIsOverdue(0);// 未逾期
		long count = repayOrderMapper.getRepayOrderCount(entity);
		Page<RepayOrder> page = new Page<RepayOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(repayOrderMapper.getRepayOrderList(entity));
		page.setTotalCount(count);
		return page;
	}

	/**
	 * @Description:贷后管理-逾期订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<RepayOrder> pageOverdueOrder(RepayOrder entity) {
		entity.setIsOverdue(1);// 逾期
		long count = repayOrderMapper.getRepayOrderCount(entity);
		Page<RepayOrder> page = new Page<RepayOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(repayOrderMapper.getRepayOrderList(entity));
		page.setTotalCount(count);
		
		 buildOverdue( );
		return page;
	}
	/**
	 * @Description:我的未结清列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public  List<RepayOrder> getUnclearedOrderByClientId(Map<String, Object> params){
		List<RepayOrder> repayOrders=repayOrderMapper.getUnclearedOrderByClientId(params);
		
		return  repayOrders;
	}
	/**
	 * @Description:贷后管理——逾期利息
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int buildOverdue( ) {
		//还款列表（未结清）
		RepayOrder entity=new RepayOrder();
		List<RepayOrder> repayOrders=repayOrderMapper.getUnclearedOrderList(entity);
		if (repayOrders.size() > 0) {
			LOGGER.info("===========================================当前未结清还款订单数量："+repayOrders.size()+"===========");
			for (int i = 0; i < repayOrders.size(); i++) {
				RepayOrder rOrder = repayOrders.get(i);
				OffsetDateTime exTime = rOrder.getExpirationTime();// 逾期时间
				OffsetDateTime nowTime = OffsetDateTime.now();// 当前时间
				Timestamp exTimeTamp=Timestamp.from(exTime.toInstant());
				Timestamp nowTimeTamp=Timestamp.from(nowTime.toInstant());
				LocalDate exTimeS=exTime.toLocalDate();
				LocalDate nowTimeS=nowTime.toLocalDate();
				if (nowTimeS.isAfter(exTimeS)  || nowTimeS.equals(exTimeS)) {//逾期了
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("rOrderId", rOrder.getId());
					long overdueCount = repayOrderMapper.getTodayOverdueCount(params);
					LOGGER.info("===========================================当前逾期订单编号："+rOrder.getOrderNo()+"=========当天计息次数overdueCount："+overdueCount+"===========");
					if (overdueCount == 0) {
						/** 逾期天数、逾期等级、逾期金额、 */
						int overdueDays = DateTimeUtil.daysDifference( exTimeTamp ,nowTimeTamp);// 逾期天数
						overdueDays=overdueDays+1;
						int overdueGrade = getAbsTimeDiffMonth(exTime.toLocalDateTime(),nowTime.toLocalDateTime());// 逾期等级
						overdueGrade=overdueGrade+1;
						String overdueGradeStr = "M" + overdueGrade;
						LOGGER.info("===========================================逾期订单编号："+rOrder.getOrderNo()+"===逾期天数overdueDays："+overdueDays+"===逾期天数overdueGradeStr："+overdueGradeStr+"===========");
						BigDecimal repayAmount = rOrder.getRepayAmount();// 当前应还金额
						BigDecimal overdueAmount = repayAmount.multiply(rOrder.getOverdueRate()).multiply(new BigDecimal(overdueDays));// 逾期金额
						// 新的应还金额
						BigDecimal newRepayAmount = repayAmount.add(overdueAmount);
						/** 记录逾期利息 */
						OverdueDetail oDetail = new OverdueDetail();
						oDetail.setRepayOrderId(rOrder.getId());
						oDetail.setRepayAmount(repayAmount);
						oDetail.setOverdueAmount(overdueAmount);
						oDetail.setOverdueDays(overdueDays);
						oDetail.setOverdueGrade(overdueGradeStr);
						oDetail.setCreateTime(OffsetDateTime.now());
						overdueDetailMapper.insert(oDetail);
						/** 更新还款记录 */
						RepayOrder newRepayOrder = new RepayOrder();
						newRepayOrder.setId(rOrder.getId());
						newRepayOrder.setRepayAmount(newRepayAmount);
						newRepayOrder.setIsOverdue(1);// 逾期
						newRepayOrder.setOverdueDays(overdueDays);
						newRepayOrder.setOverdueAmount(overdueAmount);
						newRepayOrder.setOverdueGrade(overdueGradeStr);
						newRepayOrder.setUpdateTime(OffsetDateTime.now());
						repayOrderMapper.update(newRepayOrder);
					}
				}
			}
		}
		return 1;
	}
	 /** 
     * 计算两个时间LocalDateTime相差的月数，不考虑日期前后，返回结果>=0 
     * 
     * @param before 
     * @param after 
     * @return 
     */  
    public int getAbsTimeDiffMonth(LocalDateTime before, LocalDateTime after) {  
  
        return Math.abs(Period.between(before.toLocalDate(), after.toLocalDate()).getMonths());  
    }
    /**
     * @Description:贷后管理-还款订单列表-还款短信
     * @author likun
     * @Create Time: 2017年11月2日上午10:33:00
     */
	public int repaySendSMS(RepayOrder repayOrder,Long userId) {
		/**还款短信*/
		int returnInt = 0;
		RepayOrder repayOrderData=repayOrderMapper.getRepaySendSMSInfo(repayOrder.getId());
		Map<String, String> params = dictService.getSmsDataConfig(0);
		
		StringBuilder content=new StringBuilder();
		content=content.append(repayOrderData.getRealName())
				.append(",您好，您的借款订单号：").append(repayOrderData.getOrderNo())
				.append(",本期应还金额：").append(repayOrderData.getRepayAmount())
				.append(",到期时间：").append(repayOrderData.getExpirationTime())
				.append(",请及时还款，逾期会影响您的征信信用");
		params.put("content", content.toString());
		params.put("mobile", repayOrderData.getPhone());
		//参数：0 表示该短信为接口短信
		returnInt = SmsCodeUtil.sendSmsCode(params);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,repayOrder.getId(),2,"发送还款短信:"+content);
		return returnInt;
	}
	 /**
     * @Description:贷后管理-还款订单列表-还款备注
     * @author likun
     * @Create Time: 2017年11月2日上午10:33:00
     */
	public int repayrRemark(RepayOrder repayOrder, Long userId) {
		/**更新还款订单备注*/
		RepayOrder newRepayOrder=new RepayOrder();
		newRepayOrder.setId(repayOrder.getId());
		newRepayOrder.setRemark(repayOrder.getRemark());
		repayOrderMapper.update(newRepayOrder);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,repayOrder.getId(),2,"添加还款备注:"+repayOrder.getRemark());
		return 1;
	}
	 /**
     * @Description:贷后管理-还款订单列表-查看详情
     * @author likun
     * @Create Time: 2017年11月2日上午10:33:00
     */
	public RepayOrder getRepayOrderDetail(RepayOrder repayOrder) {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("id",repayOrder.getId());
		return repayOrderMapper.getRepayOrderDetail(params);
	}  
	
	/**
	 * @Description:我的还款记录
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<RepayOrder> pageMyRepayOrder(RepayOrder entity) {
		long count = repayOrderMapper.getMyRepayOrdeCount(entity);
		Page<RepayOrder> page = new Page<RepayOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(repayOrderMapper.getMyRepayOrderList(entity));
		page.setTotalCount(count);
		return page;
	}
    /**
     * @Description:立即还款
     * @author likun
     * @Create Time: 2017年11月15日上午10:47:48
     * @param repayOrder
     * @return
     */
	public int repayment(RepayOrder repayOrder) {
		/**获取当前还款金额*/
		BigDecimal thisRepayAmount=repayOrder.getRepayAmount();
		long clientId=repayOrder.getClientId();
		/***/
		RepayOrder  newRepayOrder=new RepayOrder();
		/**当前未结清还款订单*/
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("statusType", 1);//查询未结清的还款
		params.put("clientId", clientId);
		RepayOrder waitRepayOrder= repayOrderMapper.getRepayOrderDetail(params);
		if( waitRepayOrder == null){
			return 1;
		}
		BigDecimal repayAmount=waitRepayOrder.getRepayAmount();
		BigDecimal actualRepayment=waitRepayOrder.getActualRepayment();
		/**更新还款记录*/
		if(thisRepayAmount.compareTo(repayAmount) == 0 || thisRepayAmount.compareTo(repayAmount) ==1){
			newRepayOrder.setStatus(2);//已结清
		}else{
			newRepayOrder.setStatus(1);//还款中
		}
		BigDecimal newRepayAmount=repayAmount.subtract(thisRepayAmount);
		BigDecimal newActualRepayment=actualRepayment.add(thisRepayAmount);
		newRepayOrder.setRepayAmount(newRepayAmount);
		newRepayOrder.setActualRepayment(newActualRepayment);
		newRepayOrder.setId(waitRepayOrder.getId());
		newRepayOrder.setUpdateTime(OffsetDateTime.now());
		repayOrderMapper.update(newRepayOrder);
		/**生成还款流水记录*/
		RepayDetail repayDetail=new RepayDetail();
		repayDetail.setOrderId(waitRepayOrder.getId());
		repayDetail.setOrderType(2);
		repayDetail.setAmount(thisRepayAmount);
		repayDetail.setRepayType(3);
		repayDetail.setCreateTime(OffsetDateTime.now());
		repayDetail.setRemark("还款");
		repayDetailMapper.insert(repayDetail);
		return 1;
	}
    /**
     * @Description:定时代扣
     * @author likun
     * @Create Time: 2017年11月16日上午10:24:39
     * @return
     */
	public int withhold() {
		//代扣订单—未结清且未逾期还款订单（逾期时间前一天）
		List<RepayOrder> rOrders=repayOrderMapper.getNotOverdueOrderList();
		LOGGER.info("========未结清且未逾期还款订单:"+rOrders);
		return 1;
	}
}
